/**
 * Created by scutterry on 16/6/29.
 */
define(['jquery', 'md5'], function($, md5){
    var imgData;
    var f = function(){

    };

    f.FAKE_DATA = window.location.href.indexOf("debug=1") > -1;
//    f.FAKE_DATA = true;

    f.md5 = new md5();
    f.SERVER = "http://g.gdalpha.com:8080/";
    // f.SERVER = "http://192.168.1.107:8000/";
    if(window.location.href.indexOf("andytest") > -1){
        f.SERVER = "http://andytest.nvzhanshen.com:10009/";
    }


    function getData(func){
        $.get("imgs/aofei.json", function(data){
            if(typeof data === "object"){
                imgData = data;
            }else if(typeof data === "string"){
                try{
                    imgData = JSON.parse(data);
                }catch(e){
                    alert("图片 json 解析错误");
                }
            }else{
                console.log("error type of json data");
            }
            func();
        });
    }

    function setLoadingBase(){
        $("#mengImg").attr("src", imgData["imacss-meng"]);
        $("#logoImg").attr("src", imgData["imacss-logo"]);
        $("#xianImg").attr("src", imgData["imacss-xingkuang"]);
    }

    function setLoginBase(){
        $(".aofeiLogoImg").attr("src", imgData["imacss-aofei_icon_3x"]);
        $("#tipTitleIcon").attr("src", imgData["imacss-tsfh"]);
        setLoadingBase();
    }

    function setRegBase(){
        $(".aofeiLogoImg").attr("src", imgData["imacss-aofei_icon_3x"]);
        $("#tipTitleIcon").attr("src", imgData["imacss-tsfh"]);
        $(".success_img").attr("src", imgData["imacss-success"]);
        setLoadingBase();
    }

    f.initLoadingRes = function(func){
        if(!imgData){
            getData(function(){
                setLoadingBase();
                if(typeof func === "function"){
                    func();
                }
            });
        }else{
            setLoadingBase();
            if(typeof func === "function"){
                func();
            }
        }
    };

    f.initLoginRes = function(){
        if(!imgData){
            getData(function(){
                setLoginBase();
            });
        }else{
            setLoginBase();
        }

    };

    f.initRegister = function(){
        if(!imgData){
            getData(function(){
                setRegBase();
            });
        }else{
            setRegBase();
        }
    };

    var getCodeStr = "获取手机验证码";
    var waitStr = "秒重新获取";
    var loginCode = -1;
    f.loginCount = function(span){
        var leftTime = 120;
        span.html(leftTime + waitStr);
        loginCode = setInterval(function(){
            leftTime--;
            span.html(leftTime + waitStr);
            if(leftTime <= 0){
                span.html(getCodeStr);
                clearInterval(loginCode);
                loginCode = -1;
            }
        }, 1000);
    };

    var registerCode = -1;
    f.registerCount = function(span){
        var leftTime = 120;
        span.html(leftTime + waitStr);
        registerCode = setInterval(function(){
            leftTime--;
            span.html(leftTime + waitStr);
            if(leftTime <= 0){
                span.html(getCodeStr);
                clearInterval(registerCode);
                registerCode = -1;
            }
        }, 1000);
    };

    var registerValidCode = "";
    f.generateValid = function(imgs){
        var str = Math.floor(Math.random() * 10000).toString();
        while(str.length < 4){
            str = "0" + str;
        }
        for(var i = 0; i < 4; i++){
            imgs.eq(i).attr("src", imgData["imacss-" + str[i]]);
        }
        return str;
    };

    var tipInitFlag = false;
    f.showTip = function(content){
        $("#tipContent").html(content);
        var div = $("#tipDiv");
        div.fadeIn();
        var mask = $("#maskDiv");
        mask.fadeIn();
        if(!tipInitFlag){
            tipInitFlag = true;
            mask.on("click", function(){
                mask.fadeOut();
                div.fadeOut();
            });

            $("#tipOkBtn").on("click", function(){
                mask.fadeOut();
                div.fadeOut();
            });
        }
    };

    f.isLogin = function(sessid, func){
        var obj = {};
        obj.sessid = sessid;
        var  url = f.SERVER + "ajax_is_login";
        var type = "post";
        if(f.FAKE_DATA){
            url = "./fake/aofei/is_login.json";
            type = "get";
        }
        var ajaxObj =
            {
                url: url,
                data: JSON.stringify(obj),
                method: type,
                dataType : "json",

                success: function(res){
                    if(typeof func === "function"){
                        func(res);
                    }
                },
                error: function(res){

                }
        };
        $.ajax(ajaxObj);

    };


    function login(){
        var url = f.SERVER + "aofei_login";
        var type = "post";
        if(f.FAKE_DATA){
            url = "./fake/aofei/login.json";
            type = "get";
        }
        var obj = {};
        obj.type = f.loginType;
        if(f.loginType === 1){
            var user = $("#userInput").val();
            var pwd = $("#pwdInput").val();
            if(!user || user === ""){
                f.showTip("帐号不能为空");
                return;
            }
            if(!pwd || pwd === ""){
                f.showTip("密码不能为空");
                return;
            }
            obj.user = user;
            obj.pwd = f.md5.hex_md5(pwd);
        }else{
            var ph = $("#phoneInput").val();
            var code = $("#phoneCodeInput").val();
            if(!ph || ph === ""){
                f.showTip("手机号码不能为空");
                return;
            }
            if(!code || code === ""){
                f.showTip("短信验证码不能为空");
                return;
            }
            var val = $("#loginValidInput").val();
            if(!val || val === ""){
                f.showTip("验证码不能为空");
                return;
            }
            if(val !== loginValidCode){
                f.showTip("验证码错误");
                return;
            }
            obj.pwd = "";
            obj.user = ph;
            obj.phoneCode = code
        }

        postData(url, type, obj,
            function(res){
                if(res.code === 0){
                    window.localStorage.setItem("sessid", res.data.sessid);
                    $(".wrapper").remove();
                    f.startGame();
                }else{
                    f.showTip(res.msg);
                }
            });
    }


    f.run = function(){
        var ls = window.localStorage;
        var sessid = ls.getItem("sessid");
        if(f.FAKE_DATA || sessid && sessid !== ""){
            f.isLogin(sessid, function(res){
                if(res.code === 0){
                    f.initLoadingRes(function(){
                        $(".wrapper").remove();
                        f.startGame();
                    });
                }else{
                    f.initLoginRes();
                    initLoginEvent();
                }
            });
        }else{
            f.initLoginRes();
            initLoginEvent();
        }
    };

    /*******************************************************************/
    /***************************** login *******************************/
    /*******************************************************************/
    var loginInitFlag = false;
    var loginValidCode;
    function initLoginEvent(){
        if(loginInitFlag){
            return;
        }
        $("#loginPanel").show();
        loginInitFlag = true;
        f.loginType = 1;
        var input = $("#userInput");
        input.focus(function(){
            $("#userInputDiv").removeClass("normal_border_color");
            $("#userInputDiv").addClass("focus_border_color");
            $("#userIcon").removeClass("normal_color");
            $("#userIcon").addClass("focus_color");
            $("#userRule").css({"background-color": "#df3343"});
        });

        input.blur(function(){
            $("#userInputDiv").addClass("normal_border_color");
            $("#userInputDiv").removeClass("focus_border_color");
            $("#userIcon").addClass("normal_color");
            $("#userIcon").removeClass("focus_color");
            $("#userRule").css({"background-color": "#ccc"});
        });



        var input2 = $("#pwdInput");
        input2.focus(function(){
            $("#pwdInputDiv").removeClass("normal_border_color");
            $("#pwdInputDiv").addClass("focus_border_color");
            $("#pwdIcon").removeClass("normal_color");
            $("#pwdIcon").addClass("focus_color");
            $("#pwdRule").css({"background-color": "#df3343"});
        });

        input2.blur(function(){
            $("#pwdInputDiv").addClass("normal_border_color");
            $("#pwdInputDiv").removeClass("focus_border_color");
            $("#pwdIcon").addClass("normal_color");
            $("#pwdIcon").removeClass("focus_color");
            $("#pwdRule").css({"background-color": "#ccc"});
        });


        var input3 = $("#phoneInput");
        input3.focus(function(){
            $("#userInputDiv").removeClass("normal_border_color");
            $("#userInputDiv").addClass("focus_border_color");
            $("#phoneIcon").removeClass("normal_color");
            $("#phoneIcon").addClass("focus_color");
            $("#phoneRule").css({"background-color": "#df3343"});
        });

        input3.blur(function(){
            $("#userInputDiv").addClass("normal_border_color");
            $("#userInputDiv").removeClass("focus_border_color");
            $("#phoneIcon").addClass("normal_color");
            $("#phoneIcon").removeClass("focus_color");
            $("#phoneRule").css({"background-color": "#ccc"});
        });

        var input4 = $("#phoneCodeInput");
        input4.focus(function(){
            $("#pwdInputDiv").removeClass("normal_border_color");
            $("#pwdInputDiv").addClass("focus_border_color");
            $("#codeIcon").removeClass("normal_color");
            $("#codeIcon").addClass("focus_color");
            $("#codeRule").css({"background-color": "#df3343"});
        });

        input4.blur(function(){
            $("#pwdInputDiv").addClass("normal_border_color");
            $("#pwdInputDiv").removeClass("focus_border_color");
            $("#codeIcon").addClass("normal_color");
            $("#codeIcon").removeClass("focus_color");
            $("#codeRule").css({"background-color": "#ccc"});
        });


        input4 = $("#loginValidInput");
        input4.focus(function(){
            $("#loginValidInputDiv").removeClass("normal_border_color");
            $("#loginValidInputDiv").addClass("focus_border_color");
            $("#loginVaildIcon").removeClass("normal_color");
            $("#loginVaildIcon").addClass("focus_color");
            $("#loginRule").css({"background-color": "#df3343"});
        });

        input4.blur(function(){
            $("#loginValidInputDiv").addClass("normal_border_color");
            $("#loginValidInputDiv").removeClass("focus_border_color");
            $("#loginVaildIcon").addClass("normal_color");
            $("#loginVaildIcon").removeClass("focus_color");
            $("#loginRule").css({"background-color": "#ccc"});
        });

        var pwdInput = $("#pwdInput");
        pwdInput.on("keypress", function(event){
            if(event.keyCode == "13"){
                login();
            }
        });

        $("#loginValidInput").on("keypress", function(event){
            if(event.keyCode == "13"){
                login();
            }
        });


        $("#pwdInputDel").on("click", function(){
            $("#pwdInput").val("");
        });

        $("#userDel").on("click", function(){
            $("#userInput").val("");
        });
        $("#phoneDel").on("click", function(){
            $("#phoneInput").val("");
        });

        $("#loginBtn").on("click", function(){
            console.log("login");
            login();
        });

        var imgs = $(".loginValidImg");
        $("#phoneDiv").hide();
        $("#phoneCodeDiv").hide();

        $("#normalLoginMode").on("click", function(){
            $("#normalLoginMode").addClass("selected_mode");
            $("#phoneLoginMode").removeClass("selected_mode");
            $("#userDiv").show();
            $("#phoneDiv").hide();

            $("#pwdDiv").show();
            $("#phoneCodeDiv").hide();
            $("#loginValidInputDiv").hide();
            f.loginType = 1;
        });
        $("#phoneLoginMode").on("click", function(){
            $("#normalLoginMode").removeClass("selected_mode");
            $("#phoneLoginMode").addClass("selected_mode");

            $("#userDiv").hide();
            $("#phoneDiv").show();

            $("#pwdDiv").hide();
            $("#phoneCodeDiv").show();
            $("#loginValidInputDiv").show();

            if(!loginValidCode){
                loginValidCode = f.generateValid(imgs);
            }
            f.loginType = 2;

        });

        $("#loginPhoneCode").on("click", function(event){
            var val = $("#phoneInput").val();
            if(val === ""){
                f.showTip("手机号码不能为空");
                return
            }
            if(loginCode !== -1){
                return;
            }

            var url = f.SERVER + "phone_code";
            var type = "post";
            if(f.FAKE_DATA){
                url = "./fake/aofei/phone_code.json";
                type = "get";
            }
            var obj = {};
            obj.phone = val;
            obj.type = 1;

            postData(url, type, obj,
                function(res){
                    if(res.code === 0){
                        var span = $(event.currentTarget);
                        f.showTip("手机短信验证码已发送，请耐心等待");
                        f.loginCount(span);
                    }else{
                        f.showTip(res.msg);
                    }
                });


        });


        $(".forget_pwd").on("click", function(){
            window.location.href = "http://my.gdalpha.com:8081/";
        });

        $(".free_reg").on("click", function(){
            $("#loginPanel").hide();
            $("#registerPanel").fadeIn();
            f.initRegister();
            initRegisterEvent();
        });



        $("#loginPhoneValidDiv").on("click", function(){
            loginValidCode = f.generateValid(imgs);
        });

    }



    /*******************************************************************/
    /*************************** register ******************************/
    /*******************************************************************/
    var initRegisterFlag = false;
    var valid2;
    function initRegisterEvent(){
        if(initRegisterFlag){
            return;
        }
        initRegisterFlag = true;
        f.registerType = 1;

        $("#normalRegisterMode").on("click", function(){
            $("#normalRegisterMode").addClass("selected_mode");
            $("#phoneRegisterMode").removeClass("selected_mode");
            f.registerType = 1;

            $("#userDiv2").show();
            $("#phoneDiv2").hide();

            $("#pwdDiv2").show();
            $("#phonePwdDiv").hide();

            $("#codeDiv").show();
            $("#phoneCodeDiv2").hide();
            $("#validInputDiv").hide();

//            $("#phoneCodeDiv2").hide();
//            $("#phoneDiv2").show();
        });


        $("#validInput").on("keypress", function(event){
            if(event.keyCode == "13"){
                register();
            }
        });
        $("#codeInput").on("keypress", function(event){
            if(event.keyCode == "13"){
                register();
            }
        });

        $("#phoneRegisterMode").on("click", function(){
            $("#normalRegisterMode").removeClass("selected_mode");
            $("#phoneRegisterMode").addClass("selected_mode");
            f.registerType = 2;

            $("#userDiv2").hide();
            $("#phoneDiv2").show();

            $("#pwdDiv2").hide();
            $("#phonePwdDiv").show();

            $("#codeDiv").hide();
            $("#phoneCodeDiv2").show();

            $("#validInputDiv").show();
            if(!valid2){
                var imgs3 = $(".validImg")
                valid2 = f.generateValid(imgs3);
            }
        });

        $("#registerBtn").on("click", function(){
            register();
        });

        $("#enterGameBtn").on("click", function(){
            $(".wrapper").remove();
            f.startGame();
        });

        var imgs = $(".normalValid");
        if(!registerValidCode){
            registerValidCode = f.generateValid(imgs);
        }
        $("#normalValidDiv").on("click", function(){
            registerValidCode = f.generateValid(imgs);
        });

        var imgs2 = $(".validImg")
        $("#phoneValidDiv").on("click", function(){
            valid2 = f.generateValid(imgs2);
        });

        $("#loginLink").on("click", function(){
            $("#registerPanel").hide();
            $("#loginPanel").fadeIn();
        });

        var input = $("#userInput2");
        input.focus(function(){
            $("#userInputDiv2").removeClass("normal_border_color");
            $("#userInputDiv2").addClass("focus_border_color");
            $("#userIcon2").removeClass("normal_color");
            $("#userIcon2").addClass("focus_color");
        });

        input.blur(function(){
            $("#userInputDiv2").addClass("normal_border_color");
            $("#userInputDiv2").removeClass("focus_border_color");
            $("#userIcon2").addClass("normal_color");
            $("#userIcon2").removeClass("focus_color");
        });

        var input2 = $("#phoneInput2");
        input2.focus(function(){
            $("#userInputDiv2").removeClass("normal_border_color");
            $("#userInputDiv2").addClass("focus_border_color");
            $("#phoneIcon2").removeClass("normal_color");
            $("#phoneIcon2").addClass("focus_color");
        });

        input2.blur(function(){
            $("#userInputDiv2").addClass("normal_border_color");
            $("#userInputDiv2").removeClass("focus_border_color");
            $("#phoneIcon2").addClass("normal_color");
            $("#phoneIcon2").removeClass("focus_color");
        });

        var input3 = $("#pwdInput2");
        input3.focus(function(){
            $("#pwdInputDiv2").removeClass("normal_border_color");
            $("#pwdInputDiv2").addClass("focus_border_color");
            $("#pwdIcon2").removeClass("normal_color");
            $("#pwdIcon2").addClass("focus_color");
        });

        input3.blur(function(){
            $("#pwdInputDiv2").addClass("normal_border_color");
            $("#pwdInputDiv2").removeClass("focus_border_color");
            $("#pwdIcon2").addClass("normal_color");
            $("#pwdIcon2").removeClass("focus_color");
        });

        var input4 = $("#phonePwdInput2");
        input4.focus(function(){
            $("#pwdInputDiv2").removeClass("normal_border_color");
            $("#pwdInputDiv2").addClass("focus_border_color");
            $("#phonePwdIcon").removeClass("normal_color");
            $("#phonePwdIcon").addClass("focus_color");
        });

        input4.blur(function(){
            $("#pwdInputDiv2").addClass("normal_border_color");
            $("#pwdInputDiv2").removeClass("focus_border_color");
            $("#phonePwdIcon").addClass("normal_color");
            $("#phonePwdIcon").removeClass("focus_color");
        });

        var input5 = $("#codeInput");
        input5.focus(function(){
            $("#codeInputDiv").removeClass("normal_border_color");
            $("#codeInputDiv").addClass("focus_border_color");
            $("#codeIcon2").removeClass("normal_color");
            $("#codeIcon2").addClass("focus_color");
        });

        input5.blur(function(){
            $("#codeInputDiv").addClass("normal_border_color");
            $("#codeInputDiv").removeClass("focus_border_color");
            $("#codeIcon2").addClass("normal_color");
            $("#codeIcon2").removeClass("focus_color");
        });

        var input6 = $("#phoneCodeInput2");
        input6.focus(function(){
            $("#codeInputDiv").removeClass("normal_border_color");
            $("#codeInputDiv").addClass("focus_border_color");
            $("#phoneCodeIcon").removeClass("normal_color");
            $("#phoneCodeIcon").addClass("focus_color");
        });

        input6.blur(function(){
            $("#codeInputDiv").addClass("normal_border_color");
            $("#codeInputDiv").removeClass("focus_border_color");
            $("#phoneCodeIcon").addClass("normal_color");
            $("#phoneCodeIcon").removeClass("focus_color");
        });

        var input7 = $("#validInput");
        input7.focus(function(){
            $("#validInputDiv").removeClass("normal_border_color");
            $("#validInputDiv").addClass("focus_border_color");
            $("#vaildIcon2").removeClass("normal_color");
            $("#vaildIcon2").addClass("focus_color");
        });

        input7.blur(function(){
            $("#validInputDiv").addClass("normal_border_color");
            $("#validInputDiv").removeClass("focus_border_color");
            $("#vaildIcon2").addClass("normal_color");
            $("#vaildIcon2").removeClass("focus_color");
        });



        $("#regUserDel").on("click", function(){
            $("#userInput2").val("");
        });
        $("#regPhoneDel").on("click", function(){
            $("#phoneInput2").val("");
        });
        $("#regPwdDel").on("click", function(){
            $("#pwdInput2").val("");
        });
        $("#regPwd2Del").on("click", function(){
            $("#phonePwdInput2").val("");
        });

        $("#registerPhoneCode").on("click", function(event){
            var val = $("#phoneInput2").val();
            if(val === ""){
                f.showTip("手机号码不能为空");
                return
            }
            if(loginCode !== -1){
                return;
            }

            var url = f.SERVER + "phone_code";
            var type = "post";
            if(f.FAKE_DATA){
                url = "./fake/aofei/phone_code.json";
                type = "get";
            }
            var obj = {};
            obj.phone = val;
            obj.type = 2;

            postData(url, type, obj,
                function(res){
                    if(res.code === 0){
                        var span = $(event.currentTarget);
                        f.showTip("手机短信验证码已发送，请耐心等待");
                        f.registerCount(span);
                    }else{
                        f.showTip(res.msg);
                    }
                });

        });
    }


    function register(){
        var url = f.SERVER + "aofei_register";
        var type = "post";
        if(f.FAKE_DATA){
            url = "./fake/aofei/login.json";
            type = "get";
        }
        var obj = {};
        obj.type = f.registerType;
        if(f.registerType === 1){
            var user = $("#userInput2").val();
            if(!user || user === ""){
                f.showTip("帐号不能为空");
                return;
            }
            var pwd = $("#pwdInput2").val();
            if(!pwd || pwd === ""){
                f.showTip("密码不能为空");
                return;
            }
            var code = $("#codeInput").val();
            if(!code || code === ""){
                f.showTip("验证码不能为空");
                return;
            }
            if(code != registerValidCode){
                f.showTip("验证码错误");
                return;
            }


            obj.user = user;
            obj.pwd = f.md5.hex_md5(pwd);
            obj.phoneCode = code;
        }else{
            var ph = $("#phoneInput2").val();
            if(!ph || ph === ""){
                f.showTip("手机号码不能为空");
                return;
            }
            var pwd2 = $("#phonePwdInput2").val();
            if(!pwd2 || pwd2 === ""){
                f.showTip("密码不能为空");
                return;
            }
            var phCode = $("#phoneCodeInput2").val();
            if(!phCode || phCode === ""){
                f.showTip("短信验证码不能为空");
                return;
            }
            var code2 = $("#validInput").val();
            if(!code2 || code2 === ""){
                f.showTip("验证码不能为空");
                return;
            }
            if(code2 != valid2){
                f.showTip("验证码错误");
                return;
            }
            obj.user = ph;
            obj.pwd = f.md5.hex_md5(pwd2);
            obj.phoneCode =code2;
        }

        postData(url, type, obj,
            function(res){
                if(res.code === 0){
                    var user, pwd;
                    if(f.registerType === 1){
                        user = $("#userInput2").val();
                        pwd = $("#pwdInput2").val();
                    }else{
                        user = $("#phoneInput2").val();
                        pwd = $("#phonePwdInput2").val();
                    }
                    $("#registerPanel").hide();
                    $("#regUser").html("您的帐号:" + user);
                    $("#regPwd").html("您的帐号:" + pwd);
                    $("#registerSuccessPanel").fadeIn();
                }
            });
    }



    function postData(url, type, data, func){
        if(!data){
            data = {};
        }
        var ua = navigator.userAgent.toLowerCase();
        data.terminal_type = ua.indexOf("mobile") > -1? "Mobile" : "PC";
        var ajaxObj = {};
        ajaxObj.url = url;
        ajaxObj.data = JSON.stringify(data);
        ajaxObj.method = type;
        ajaxObj.dataType = "json";
        ajaxObj.success = func;

        $.ajax(ajaxObj);
    }



    window.AlphaGame = f;
    return f;
});


